/*
 * simes - simulador de escalonamento de processos
 * Copyright (C) 2006  Pablo A. Lerina Rodrigues
 *                     Armando Zaro
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"
#include "colors.h"

void print_queue(t_queue *q) {
	t_qnode *tmp = malloc(sizeof(t_qnode));
	t_processo *p = malloc(sizeof(t_processo));
	tmp = q->front;
	do {
		p = (t_processo*)tmp->data;
		printf("Processo(%d) Estado(%d) Entrada(%s%d%s) Comandos(%d)\n", p->id, 
																		p->estado, GREEN,
																		p->entrada, NORMAL,
																		p->comandos);
		printf("  |");
		// itera na pilha de comandos
		t_snode *tmp_s = malloc(sizeof(t_snode));
		tmp_s = (t_snode*)p->comandos->base;
		do {
			printf("%s %d %d ", RED, tmp_s->comando, tmp_s->valor);
			if (tmp_s->down != NULL && tmp_s->up != NULL)
				printf(" <-> %s ", NORMAL);
			else if (tmp_s->up == NULL)
				printf(" %s ", NORMAL);
			else
				printf(" -> %s ", NORMAL);
		} while ((tmp_s = tmp_s->up) != 0);
		free(tmp_s);
		printf("\n");
	} while ((tmp = tmp->next) != NULL);
}

/*
 * FIFO Queue
 * Fila de prioridade ascendente, balizada por "entrada"
 */ 
void ordered_insert_pnode(t_queue *q, void *data) {
	t_qnode *node = malloc(sizeof(t_qnode));
	node->data = data;
	node->next = NULL;
	if (q->rear == NULL){
		// lista vazia
		q->front = node;
		q->rear = node;
	} else {
		if (((t_processo *)data)->entrada > ((t_processo *)q->rear->data)->entrada) {
			(q->rear)->next = node;
			q->rear = node;
		} else if(((t_processo*)data)->entrada < ((t_processo *)q->front->data)->entrada) {
			node->next = q->front;
			q->front = node;
		}
	}
}

/*
 * FIFO Queue
 * Insere nodo na fila
 */
void insert_node(t_queue *q, void *data) {
	t_qnode *node = malloc(sizeof(t_qnode));
	node->data = data;
	node->next = NULL;
	if (q->rear == NULL) // lista vazia
		q->front = node;
	else
		(q->rear)->next = node;
	q->rear = node;
}

/*
 * FIFO Queue
 */
void *remove_node(t_queue *q) {
	if (q->rear != NULL) {
		t_qnode *node = malloc(sizeof(t_qnode));
		node = (t_qnode *)q->front;
		q->front = node->next;
		if (q->front == NULL)
			q->rear = NULL;
		return node->data;
	} else {
#ifdef DEBUG
		fprintf(stderr, "A lista esta vazia.\n");
#endif
		return NULL;
//		exit(1);
	}
}
